#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
using namespace std;
class UnionFind
{
public:
    UnionFind(){};
    int Find(int x)
    {
        if (par.count(x) == 0)
        {
            par[x] = x;
            size[x] = 1;
        }
        return par[x] == x ? x : par[x] = Find(par[x]);
    }
    void Union(int x, int y)
    {
        int parx = Find(x), pary = Find(y);
        if (parx == pary)
            return;
        if (size[parx] < size[pary])
        {
            par[parx] = pary;
            size[pary] += size[parx];
        }
        else
        {
            par[pary] = parx;
            size[parx] += size[pary];
        }
    }
    int numOfClasses()
    {
        int cnt = 0;
        for (auto &[x, px] : par)
        {
            if (x == px)
                cnt++;
        }
        return cnt;
    }

private:
    map<int, int> par, size;
};

class Solution
{
public:
    UnionFind uf;
    int removeStones(vector<vector<int>> &stones)
    {
        for (auto &s : stones)
        {
            uf.Union(s[0], s[1] + 10001);
        }
        return stones.size() - uf.numOfClasses();
    }
};